<?php
declare (strict_types = 1);

namespace app\command;

use app\api\consDir\OrderPrefixConst;
use app\api\consDir\SandConst;
use app\api\services\AlipayService;
use app\api\services\CommunityService;
use app\api\services\MemberService;
use app\api\services\SandService;
use app\common\models\Community\CommunityOrder;
use app\common\models\Community\PrepayCommunityOrder;
use app\common\models\Order\OrderPay;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Log;

class PrepayCommunityRefund extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('prepay community refund')
            ->setDescription('the prepay community refund command');
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    protected function execute(Input $input, Output $output)
    {
        $time = CommunityService::getInstance()->getCommunityConfig('settlement_time');
        [$startTime,$endTime] = explode('-',$time[0]);
        $prepayTimeout = (int)CommunityService::getInstance()->getCommunityConfig('prepay_timeout') ?: 0;
        $prepayRefundTime = (int)CommunityService::getInstance()->getCommunityConfig('prepay_refund_time') ?: 0;
        $minutes = $prepayTimeout + $prepayRefundTime;
        $start = date('Y-m-d H:i:s',strtotime("+{$minutes} minutes",strtotime($startTime)));
        $now = date('Y-m-d H:i:s');
        if($now < $start){
            return false;
        }

        $yesterdayStart = date('Y-m-d 00:00:00',strtotime('-1 day'));
        $yesterdayEnd = date('Y-m-d 23:59:59', strtotime('-1 day'));
        $where = [
            ['is_deal_refund','=',0],
            ['is_turn','=',1],
            ['is_final','=',0],
            ['create_at','between',[$yesterdayStart,$yesterdayEnd]],
        ];
        $list = PrepayCommunityOrder::getInstance()->where($where)->select();
        if(empty($list)){
            return false;
        }
        foreach($list as $v){
            $map = [
                ['order_no','=',$v['order_no']],
            ];
            $payNo = OrderPay::getInstance()->where($map)->order('id desc')->value('pay_no');
            try {
                //'1微信 2支付宝 3余额 4杉德'
                if ($v['payType'] == 2) {
                    $aliOrder = AlipayService::getInstance()->find($payNo);
                    if (!empty($aliOrder) && $aliOrder['code'] == 10000) {
                        //退款 更新状态
                        $ret = AlipayService::getInstance()->refund($payNo, $aliOrder['total_amount']);
                        if (!empty($ret) && $ret['code'] == 10000) {
                            $v->is_refund = 1;
                            $v->refund_time = date('Y-m-d H:i:s');
                        }
                    }
                } elseif ($v['payType'] == 4) {
                    $price = env('test.is_test') == 1 ? 0.01 : $v['payPrice'];
                    //平台社区
                    $ret = [];
                    //杉德查询到消费订单
                    $orderQuery = SandService::getInstance()->orderQuery($payNo);
                    if (isset($orderQuery['orderStatus']) && $orderQuery['orderStatus'] == 'success') {
                        $ret = SandService::getInstance()->orderRefund($v['order_no'], $payNo, $price);
                    }

                    if (isset($ret['resultStatus']) && $ret['resultStatus'] == 'success') {
                        $v->is_refund = 1;
                        $v->refund_time = date('Y-m-d H:i:s');
                    }
                }elseif ($v['payType'] == 3) {
                    //余额
                    if ($v['payPrice'] > 0) {
                        $msg = '退还预付金额' . $v['payPrice'];
                        MemberService::getInstance()->addFinanceLog($v['userId'], 'prepay_refund', $v['payPrice'], 1, $msg, $v['orderNo']);
                        $v->is_refund = 1;
                        $v->refund_time = date('Y-m-d H:i:s');
                    }
                }
                //取消订单
                $v->update_at = date('Y-m-d H:i:s');
                $v->is_deal_refund = 1;
                $v->save();
            } catch (\Exception $e) {
                Log::error($v['orderNo'] . $e->getMessage());
            }

        }
        // 指令输出
        $output->writeln('prepay community refund');
    }
}
